package com.chuanke.ckfamily.service.common.impl;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.chuanke.ckfamily.dao.common.TipsDao;
import com.chuanke.ckfamily.dao.common.model.TeamCreateLog;
import com.chuanke.ckfamily.dao.common.model.Tips;
import com.chuanke.ckfamily.dao.social.model.Family;
import com.chuanke.ckfamily.dao.social.model.FamilyMember;
import com.chuanke.ckfamily.dao.user.UserDao;
import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.common.CreateSystemFamilyService;
import com.chuanke.ckfamily.service.common.TeamCreateLogService;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.constant.Constant;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.social.FamilyMemberService;
import com.chuanke.ckfamily.service.social.FamilyService;
import com.chuanke.ckfamily.service.user.UserService;
import com.chuanke.ckfamily.service.util.CkServerUtil;
import com.weijie.core.BaseBiz;
import com.weijie.corel.wy.request.WyTeamAddRequest;

@Service
@Transactional
public class CreateSystemFamilyServiceImpl extends BaseBiz<Tips, TipsDao> implements CreateSystemFamilyService {

	private static final Logger logger = LoggerFactory.getLogger(CreateSystemFamilyServiceImpl.class);

	@Autowired
	private WyService wyService;

	@Autowired
	private TeamCreateLogService teamCreateLogService;

	@Autowired
	private UserService userService;

	@Autowired
	private FamilyService familyService;

	@Autowired
	private FamilyMemberService familyMemberService;

	@Autowired
	private UserDao userDao;

	@Override
	public void initHead() throws ParseException, CFException, IOException {
		List<kefu> list = new ArrayList<>();
		list.add(new kefu(70, "晨曦家族"));
		list.add(new kefu(110165, "荔枝团子"));
		list.add(new kefu(52, "赚他一个亿"));
		list.add(new kefu(64, "钻石家族"));
		list.add(new kefu(158835, "皇亲国戚"));
		list.add(new kefu(26526, "名门望族"));
		list.add(new kefu(60, "轻松赚钱"));
		list.add(new kefu(673997, "黄金矿工"));
		list.add(new kefu(286, "网赚之家"));
		list.add(new kefu(62, "赚啊赚啊赚"));
		list.add(new kefu(734030, "传客大师"));
		list.add(new kefu(725454, "快乐赚钱"));
		list.add(new kefu(725493, "转发客联盟"));
		list.add(new kefu(712614, "乱舞春秋"));
		list.add(new kefu(726657, "赚钱先锋"));
		list.add(new kefu(732291, "传客分队"));
		list.add(new kefu(732333, "日进斗金"));
		list.add(new kefu(732336, "红包不停"));
		list.add(new kefu(732339, "达官贵人"));
		list.add(new kefu(740921, "赚客大师"));

		logger.debug("=========>创建系统家族");

//		List<TeamCreateLog> teams = teamCreateLogService.findTeamCreateLog();
//		for (TeamCreateLog teamCreateLog : teams) {
//			try {
//				wyService.removeTeam(teamCreateLog.getTid(), teamCreateLog.getOwner_user_no());
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}

		for (kefu kf : list) {
			Long uid = kf.getId().longValue();
			String fname = kf.getFname();
			User tuser = userDao.findById(uid);
			if (tuser != null) {
				logger.debug("============>用户已经存在。uid={}", uid);
				continue;
			}

			User user = CkServerUtil.loadUser(uid);
			if (user == null) {
				logger.debug("=============>用户创客不存在。uid={}", uid);
				continue;
			}

			user.setIs_admin(1);
			user.setIs_header(1);

			String wy_token = wyService.registUser(user);
			if (wy_token == null) {
				logger.debug("=============>注册云信失败。uid={}", uid);
				continue;
			}
			user.setWy_token(wy_token);
			userService.save(user);

			Family family = new Family();
			family.setAnnouncement("");
			family.setBalance(0l);
			family.setCreate_time(new Timestamp(System.currentTimeMillis()));
			family.setUpdate_time(new Timestamp(System.currentTimeMillis()));
			family.setFicon(Constant.family_default_icon);
			family.setIntro("");
			family.setName(fname);
			family.setType(2);
			family.setOwner_user_id(user.getId());
			family.setOwner_user_no(user.getUser_no());
			family.setSuper_id(user.getSuper_id());
			family.setFcapacity(500);
			family.setMnum(1);

			String tid = wyService.createTeam(family);
			if (tid == null) {
				logger.debug("=============>创建云信群失败。uid={}", uid);
			}
			family.setTid(tid);

			familyService.save(family);

			FamilyMember fm = new FamilyMember();
			fm.setFamily_id(family.getId());
			fm.setDevote(0l);
			fm.setDevote_sum(0l);
			fm.setIs_delete(0);
			fm.setMute(0);
			fm.setMute_num(null);
			fm.setMute_time(null);
			fm.setNick_name(user.getNick_name());
			fm.setUser_id(user.getId());
			fm.setUpdate_time(new Timestamp(System.currentTimeMillis()));
			fm.setCreate_time(new Timestamp(System.currentTimeMillis()));
			fm.setNocall(0);
			fm.setVersion("");
			familyMemberService.save(fm);

			wyService.addTeamMember(family, user.getUser_no());
		}

	}

	class kefu {
		private Integer id;
		private String fname;

		public kefu(Integer id, String fname) {
			super();
			this.id = id;
			this.fname = fname;
		}

		public Integer getId() {
			return id;
		}

		public void setId(Integer id) {
			this.id = id;
		}

		public String getFname() {
			return fname;
		}

		public void setFname(String fname) {
			this.fname = fname;
		}
	}
	


	@Override
	public void updateOwner(Long[] ids) throws CFException {
		long oldId=ids[0];
		long newId=ids[1];
		User newUser = userService.findById(newId);
		User oldUser = userService.findById(oldId);
		if(newUser==null || oldUser==null){
			
			logger.debug("用户不存在");
			return;
		}
		if(!(oldUser.getIs_header()!=null && oldUser.getIs_header()==1) ){
			logger.debug("用户不是群主");
			return;
		}
		
		Family family = familyService.findFamilyByUserId(oldId);
		if(family==null){
			logger.debug("家族不存在");
			return;
		}
		FamilyMember oldMember = familyMemberService.findByUserId(oldId);
		if(oldMember==null){
			logger.debug("家族成员不存在");
			return;
		}
		FamilyMember newMember = familyMemberService.findByUserId(newId);
		if(newMember==null){
			logger.debug("家族成员不存在");
			return;
		}
		
		   WyTeamAddRequest request=new WyTeamAddRequest();
	       request.setTid(family.getTid());
	       request.setOwner(family.getOwner_user_no());
	       request.setMembers(JSONArray.toJSONString(Arrays.asList(newUser.getUser_no())));
	       request.setMsg("欢迎加入家族");
		
		if(newMember!=null){
			FamilyMember memberParam2=new FamilyMember();
			memberParam2.setId(newMember.getId());
			memberParam2.setIs_delete(1);
			memberParam2.setVersion(UUID.randomUUID().toString());
			memberParam2.setUpdate_time(new Timestamp(System.currentTimeMillis()));
			familyMemberService.update(memberParam2);
		}
		
		if(oldMember!=null){
			FamilyMember memberParam=new FamilyMember();
			memberParam.setId(oldMember.getId());
			memberParam.setIs_delete(1);
			memberParam.setVersion(UUID.randomUUID().toString());
			memberParam.setUpdate_time(new Timestamp(System.currentTimeMillis()));
			familyMemberService.update(memberParam);
		}
		
		
		User userParam=new User();
		userParam.setId(newUser.getId());
		userParam.setIs_admin(1);
		userParam.setIs_header(1);
		
		String wy_token = wyService.registUser(newUser);
		if (wy_token == null) {
			logger.debug("=============>注册云信失败。uid={}", oldId);
			logger.debug("注册云信失败");
		}
		userParam.setWy_token(wy_token);
		userService.update(userParam);
		
		User userParam2=new User();
		userParam2.setId(oldUser.getId());
		userParam2.setIs_admin(0);
		userParam2.setIs_header(0);
		userService.update(userParam2);
		
		//网易修改群主
		boolean b=wyService.changeOwner(family.getTid(),family.getOwner_user_no(),newUser.getUser_no());
		
		//修改群
		Family familyParam=new Family();
		familyParam.setId(family.getId());
		familyParam.setOwner_user_id(newUser.getId());
		familyParam.setOwner_user_no(newUser.getUser_no());
		familyParam.setSuper_id(newUser.getSuper_id());
		familyService.update(familyParam);
		
		
		FamilyMember fm = new FamilyMember();
		fm.setFamily_id(family.getId());
		fm.setDevote(0l);
		fm.setDevote_sum(0l);
		fm.setIs_delete(0);
		fm.setMute(0);
		fm.setMute_num(null);
		fm.setMute_time(null);
		fm.setNick_name(newUser.getNick_name());
		fm.setUser_id(newUser.getId());
		fm.setUpdate_time(new Timestamp(System.currentTimeMillis()));
		fm.setCreate_time(new Timestamp(System.currentTimeMillis()));
		fm.setNocall(0);
		fm.setVersion("");
		familyMemberService.save(fm);
		
		
		
		
	}
}